import React, { useState, useEffect } from 'react';
import { Card, Statistic, Row, Col, Progress, Space, Tag, Tooltip } from 'antd';
import {
  ClockCircleOutlined,
  FileTextOutlined,
  DollarOutlined,
  ThunderboltOutlined,
  BarChartOutlined,
  InfoCircleOutlined
} from '@ant-design/icons';
import { ModelType, MODEL_INFO } from '@/types/models';
import './style.css';

interface PerformanceData {
  responseTime: number;      // milliseconds
  firstTokenTime?: number;   // time to first token
  inputTokens: number;
  outputTokens: number;
  totalTokens: number;
  cost: number;              // in CNY
  model: ModelType;
}

interface PerformanceMetricsProps {
  currentData?: PerformanceData;
  sessionData?: PerformanceData[];
  showDetails?: boolean;
  className?: string;
}

const PerformanceMetrics: React.FC<PerformanceMetricsProps> = ({
  currentData,
  sessionData = [],
  showDetails = true,
  className = ''
}) => {
  const [totalMetrics, setTotalMetrics] = useState({
    totalTokens: 0,
    totalCost: 0,
    avgResponseTime: 0,
    requestCount: 0
  });

  useEffect(() => {
    if (sessionData.length > 0) {
      const totals = sessionData.reduce((acc, data) => ({
        totalTokens: acc.totalTokens + data.totalTokens,
        totalCost: acc.totalCost + data.cost,
        totalResponseTime: acc.totalResponseTime + data.responseTime,
        requestCount: acc.requestCount + 1
      }), {
        totalTokens: 0,
        totalCost: 0,
        totalResponseTime: 0,
        requestCount: 0
      });

      setTotalMetrics({
        totalTokens: totals.totalTokens,
        totalCost: totals.totalCost,
        avgResponseTime: totals.totalResponseTime / totals.requestCount,
        requestCount: totals.requestCount
      });
    }
  }, [sessionData]);

  const getSpeedLevel = (responseTime: number) => {
    if (responseTime < 1000) return { level: 'fast', color: '#52c41a', text: '快速' };
    if (responseTime < 3000) return { level: 'medium', color: '#faad14', text: '中等' };
    return { level: 'slow', color: '#ff4d4f', text: '较慢' };
  };

  const formatTime = (ms: number) => {
    if (ms < 1000) return `${ms.toFixed(0)}ms`;
    return `${(ms / 1000).toFixed(2)}s`;
  };

  const formatCost = (cost: number) => {
    if (cost < 0.01) return `￥${cost.toFixed(4)}`;
    return `￥${cost.toFixed(3)}`;
  };

  return (
    <div className={`performance-metrics ${className}`}>
      {currentData && (
        <Card 
          title={
            <Space>
              <BarChartOutlined />
              <span>当前请求性能</span>
              <Tag color="blue">{MODEL_INFO[currentData.model].name}</Tag>
            </Space>
          }
          className="metrics-current"
          size="small"
        >
          <Row gutter={[16, 16]}>
            <Col xs={12} sm={6}>
              <Statistic
                title={
                  <Space>
                    <ClockCircleOutlined />
                    <span>响应时间</span>
                  </Space>
                }
                value={formatTime(currentData.responseTime)}
                suffix={
                  <Tag color={getSpeedLevel(currentData.responseTime).color}>
                    {getSpeedLevel(currentData.responseTime).text}
                  </Tag>
                }
              />
            </Col>
            <Col xs={12} sm={6}>
              <Statistic
                title={
                  <Space>
                    <FileTextOutlined />
                    <span>Token用量</span>
                  </Space>
                }
                value={currentData.totalTokens}
                suffix={
                  <Tooltip title={`输入: ${currentData.inputTokens} | 输出: ${currentData.outputTokens}`}>
                    <InfoCircleOutlined style={{ fontSize: 14, color: '#8c8c8c' }} />
                  </Tooltip>
                }
              />
            </Col>
            <Col xs={12} sm={6}>
              <Statistic
                title={
                  <Space>
                    <DollarOutlined />
                    <span>本次成本</span>
                  </Space>
                }
                value={formatCost(currentData.cost)}
                valueStyle={{ color: '#52c41a' }}
              />
            </Col>
            <Col xs={12} sm={6}>
              <Statistic
                title={
                  <Space>
                    <ThunderboltOutlined />
                    <span>首Token时间</span>
                  </Space>
                }
                value={currentData.firstTokenTime ? formatTime(currentData.firstTokenTime) : '-'}
              />
            </Col>
          </Row>

          {showDetails && (
            <div className="metrics-details">
              <Row gutter={[16, 8]}>
                <Col span={12}>
                  <div className="detail-item">
                    <span className="detail-label">输入/输出比例</span>
                    <Progress
                      percent={100}
                      success={{
                        percent: (currentData.inputTokens / currentData.totalTokens) * 100
                      }}
                      showInfo={false}
                      strokeColor="#1890ff"
                    />
                    <span className="detail-value">
                      {currentData.inputTokens} / {currentData.outputTokens}
                    </span>
                  </div>
                </Col>
                <Col span={12}>
                  <div className="detail-item">
                    <span className="detail-label">生成速度</span>
                    <span className="detail-value">
                      {currentData.responseTime > 0 
                        ? `${(currentData.outputTokens / (currentData.responseTime / 1000)).toFixed(1)} tokens/s`
                        : '-'
                      }
                    </span>
                  </div>
                </Col>
              </Row>
            </div>
          )}
        </Card>
      )}

      {sessionData.length > 0 && (
        <Card
          title={
            <Space>
              <BarChartOutlined />
              <span>会话统计</span>
            </Space>
          }
          className="metrics-session"
          size="small"
        >
          <Row gutter={[16, 16]}>
            <Col xs={12} sm={6}>
              <Statistic
                title="总请求数"
                value={totalMetrics.requestCount}
                prefix={<FileTextOutlined />}
              />
            </Col>
            <Col xs={12} sm={6}>
              <Statistic
                title="总Token"
                value={totalMetrics.totalTokens}
                prefix={<FileTextOutlined />}
              />
            </Col>
            <Col xs={12} sm={6}>
              <Statistic
                title="总成本"
                value={formatCost(totalMetrics.totalCost)}
                prefix={<DollarOutlined />}
                valueStyle={{ color: totalMetrics.totalCost > 1 ? '#ff4d4f' : '#52c41a' }}
              />
            </Col>
            <Col xs={12} sm={6}>
              <Statistic
                title="平均响应"
                value={formatTime(totalMetrics.avgResponseTime)}
                prefix={<ClockCircleOutlined />}
              />
            </Col>
          </Row>

          {showDetails && sessionData.length > 0 && (
            <div className="metrics-chart">
              <div className="chart-title">模型使用分布</div>
              <Row gutter={[8, 8]}>
                {Object.values(ModelType).map(model => {
                  const count = sessionData.filter(d => d.model === model).length;
                  if (count === 0) return null;
                  const percentage = (count / sessionData.length) * 100;
                  
                  return (
                    <Col key={model} span={24}>
                      <div className="model-usage">
                        <span className="model-name">{MODEL_INFO[model].name}</span>
                        <Progress
                          percent={percentage}
                          size="small"
                          format={() => `${count}次`}
                        />
                      </div>
                    </Col>
                  );
                })}
              </Row>
            </div>
          )}
        </Card>
      )}
    </div>
  );
};

export default PerformanceMetrics;